package pl.edu.pw.MidEmu.Logic;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

/**
 * Service class responsible for maintaining network connectivity matrix
 * @author Mateusz Starodab
 *
 */
public class RuleWriter
{
	/**
	 * Adds connectivity rule
	 * @param sourceIP Source IP address
	 * @param destinationIP Destination IP address
	 */
	public static void AddRule(String sourceIP, String destinationIP)
	{
		String ruleToAdd = sourceIP + ";" + destinationIP;

		try
		{
			BufferedWriter output = new BufferedWriter(new FileWriter("./temp/rules.txt", true));
			output.write(ruleToAdd);
			output.newLine();
			output.flush();
			output.close();
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}

		System.out.println("Rule " + ruleToAdd + " added");
	}

	/**
	 * Removes connectivity rule
	 * @param sourceIP Source IP address
	 * @param destinationIP Destination IP address
	 */
	public static void RemoveRule(String sourceIP, String destinationIP)
	{
		String ruleToRemove = sourceIP + ";" + destinationIP;
		StringBuilder sb = new StringBuilder();

		try
		{
			BufferedReader input = new BufferedReader(new FileReader("./temp/rules.txt"));
			String line;
			while ((line = input.readLine()) != null)
			{
				sb.append(line);
				sb.append("\n");
			}

			input.close();
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}

		int startIndex = sb.indexOf(ruleToRemove);

		sb.delete(startIndex, startIndex + ruleToRemove.length()+1);

		try
		{
			BufferedWriter output = new BufferedWriter(new FileWriter("./temp/rules.txt", false));
			output.write(sb.toString());
			output.flush();
			output.close();
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		
		System.out.println("Rule " + ruleToRemove + " removed");
	}
}
